 <?php
include_once FANWE_ROOT.'sdks/taobao/TopClient.php';
include_once FANWE_ROOT.'sdks/taobao/request/ItemGetRequest.php';
include_once FANWE_ROOT.'sdks/taobao/request/ShopGetRequest.php';
include_once FANWE_ROOT.'sdks/taobao/request/TaobaokeItemsDetailGetRequest.php';
include_once FANWE_ROOT.'sdks/taobao/request/TaobaokeItemsConvertRequest.php';

class taobao_sharegoods implements interface_sharegoods
{
	public function fetch($url)
	{
        global $_FANWE;
		$id = $this->getID($url);
		if($id == 0)
			return false;

		$key = 'taobao_'.$id;

		$disable_goods = FDB::fetchFirst('SELECT * FROM '.FDB::table('goods_disable')." WHERE keyid = '$key'");
		if($disable_goods)
		{
			$result['status'] = -2;
			return $result;
		}

		$share_goods = FDB::fetchFirst('SELECT * FROM '.FDB::table('goods')." WHERE keyid = '$key'");
		if($share_goods && $_FANWE['uid'] > 0)
		{
			$user_goods = (int)FDB::fetchFirst('SELECT * FROM '.FDB::table('share_goods').'
				WHERE uid = '.$_FANWE['uid'].' AND goods_id = '.$share_goods['id']);
			if($user_goods)
			{
				$result['status'] = -1;
				$result['share_id'] = $user_goods['share_id'];
				$result['goods_id'] = $user_goods['goods_id'];
				return $result;
			}
		}

        $is_tdj = (int)$_FANWE['cache']['business']['taobao']['is_tdj'];
        if($is_tdj){
            $result = $this->collectByUrl($id,$url,$share_goods);
        }else{
            $result = $this->collectByApi($id,$share_goods);
        }

        if($result){
            if($result['status'] < 0){
                return $result;
            }
        }else{
            return $result;
        }
		$result['status'] = 1;
		$result['item']['key'] = $key;
		$result['item']['type'] = "taobao";
		return $result;
	}

    private function collectByApi($id,$share_goods) {
        $key = 'taobao_'.$id;
        $client = new TopClient;
		$client->appkey = trim($_FANWE['cache']['business']['taobao']['app_key']);
		$client->secretKey = trim($_FANWE['cache']['business']['taobao']['app_secret']);
        $result = array();
		if(!$share_goods)
		{
			$result = getTempCache(md5($key));
			if($result === NULL)
			{
				$req = new ItemGetRequest;
                //3.1版本增加获取图片集合
				$req->setFields("detail_url,title,nick,pic_url,price,cid,delist_time,desc,item_img");
				$req->setNumIid($id);
				$resp = $client->execute($req);

				if(!isset($resp->item))
					return false;

				$share_goods = array();
				$result = array();
                $imgs = array();
				$goods = (array)$resp->item;

				if(!isset($goods['detail_url']) || !isset($goods['pic_url']))
					return false;

				if(!FS("Goods")->getIsDisableByCid('taobao',$goods['cid']))
				{
					$result['status'] = -4;
					return $result;
				}

                if(count($goods['item_imgs']->item_img)){
                    foreach($goods['item_imgs']->item_img as $img_obj){
                        if((int)$img_obj->id >0) // 除主图以外的图片
                            $imgs[] = (string)$img_obj->url;
                    }
                    $result['imgs_html'] = $this->saveWebImg($imgs); //图片集合 <li></li>结构
                }

				if(!empty($goods['nick']))
				{
					$req = new ShopGetRequest;
					$req->setFields("sid,cid,nick,title,pic_path");
					$req->setNick($goods['nick']);
					$resp = $client->execute($req);
					if(isset($resp->shop))
					{
						$shop = (array)$resp->shop;
						$result['shop']['name'] = $shop['title'];
						$result['shop']['shop_id'] = $shop['sid'];
						$result['shop']['url'] = 'http://shop'.$shop['sid'].'.taobao.com';
						$disable_shop = FDB::fetchFirst('SELECT * FROM '.FDB::table('shop_disable')." WHERE shop_url = '".$result['shop']['url']."'");
						if($disable_shop)
						{
							$result['status'] = -3;
							return $result;
						}
						$result['shop']['cid'] = FS("Shop")->getCid('taobao',$shop['cid']);
					}
				}

				$result['image_server'] = '';
				if($_FANWE['setting']['share_image_save_type'] == 0)
				{
					$image['path'] = $goods['pic_url'];
					$image['server_code'] = '';
				}
				elseif(!IS_UPYUN && FS("Image")->getIsServer())
				{
					$args = array();
					$args['pic_url'] = $goods['pic_url'];
					$server = FS("Image")->formatServer($_FANWE['request']['image_server'],'DE');
					$server = FS("Image")->getImageUrlToken($args,$server,1);
					$body = FS("Image")->sendRequest($server,'savetemp',true);
					if(empty($body))
						return false;

					$image = unserialize($body);
					$result['image_server'] = $server['image_server'];
				}
				else
				{
					$image = copyFile($goods['pic_url'],"temp",false);
					if($image === false)
						return false;
					$image['server_code'] = '';
				}
				$share_goods['img'] = $image['path'];

				if(isset($shop))
				{
					$shop_id = FS("Shop")->getShopIdByUrl($result['shop']['url']);
					if($shop_id == 0)
					{
						if(!empty($shop['pic_path']))
						{
							if($_FANWE['setting']['share_image_save_type'] == 0)
							{
								$image['path'] = 'http://logo.taobao.com/shop-logo'.$shop['pic_path'];
								$image['server_code'] = '';
							}
							elseif(!IS_UPYUN && FS("Image")->getIsServer())
							{
								$args = array();
								$args['pic_url'] = 'http://logo.taobao.com/shop-logo'.$shop['pic_path'];
								$server = FS("Image")->getImageUrlToken($args,'',1);
								$body = FS("Image")->sendRequest($server,'savetemp',true);
								if(!empty($body))
									$image = unserialize($body);
								else
									$image = false;
							}
							else
							{
								$image = copyFile('http://logo.taobao.com/shop-logo'.$shop['pic_path'],"temp",false);
								if($image === false)
									$image['server_code'] = '';
							}

							if($image !== false)
							{
								$result['shop']['logo'] = $image['path'];
								$result['shop']['server_code'] = $image['server_code'];
							}
						}
					}
					else
					{
						$share_goods['shop_id'] = $shop_id;
						unset($result['shop']);
					}
				}

				$share_goods['id'] = 0;
				$share_goods['gid'] = $id;
				$share_goods['name'] = $goods['title'];
				$share_goods['desc'] = $goods['desc'];
				$share_goods['cid'] = FS("Goods")->getCid('taobao',$goods['cid']);
				$share_goods['price'] = $goods['price'];
				$share_goods['delist_time'] = str2Time($goods['delist_time']);
				$share_goods['server_code'] = $image['server_code'];
				$share_goods['pic_url'] = $goods['pic_url'].'_100x100.jpg';
				$share_goods['url'] = $goods['detail_url'];
				$result['item'] = $share_goods;
				setTempCache(md5($key),$result);
			}
		}
		else
		{
			$share_goods['pic_url'] = getImgById($share_goods['img_id'],100,100);
			if($share_goods['cid'] == 0)
			{
				$req = new ItemGetRequest;
				$req->setFields("cid,delist_time");
				$req->setNumIid($id);
				$resp = $client->execute($req);
				if(isset($resp->item) && !empty($resp->item->cid))
				{
					$update_goods = array();
					$share_goods['cid'] = $update_goods['cid'] = FS("Goods")->getCid('taobao',$resp->item->cid);
					$share_goods['delist_time'] = $update_goods['delist_time'] = str2Time($resp->item->delist_time);
					FDB::update('goods',$update_goods,'id = '.$share_goods['id']);
				}
			}
			$result['item'] = $share_goods;
		}
        return $result;
    }

    private function collectByUrl($id,$url,$share_goods) {
        $key = 'taobao_'.$id;
        $result = array();
		if(!$share_goods)
		{
			$result = getTempCache(md5($key));
			if($result === NULL)
			{
                $content = @file_get_contents($url);
                $content = @mb_convert_encoding($content,"UTF-8","gbk");
                if(empty($content)){
                    return false;
                }
                $content = preg_replace('/[\r\n]/','',$content);
				$share_goods = array();
				$result = array();
                $imgs = array();
                $goods = array();
                $goods['detail_url'] = $url;
                if(preg_match('/<title>(.*?)<\/title>/',$content,$title)){
                    $goods['title'] = substr($title[1],0,strrpos($title[1],'-',1));
                }
                if(preg_match('/"sellerNickName"\s*:\s*\'(.*?)\',/',$content,$nick)){
                    $goods['nick'] = urldecode($nick[1]);
                }elseif(preg_match('/sellerNick\s*:\s*"(.*?)",/',$content,$nick)){
                    $goods['nick'] = $nick[1];
                }
                if(preg_match('/<ul[^<]*?id="J_UlThumb"[^>]*?>(.*?)<\/ul>/',$content,$imgs_html)){
                    preg_match_all('/<img[^<]*?src="(.*?)"[^>]*?\/>/',$imgs_html[1],$img_srcs);
                    if($img_srcs && count($img_srcs[1]) > 0){
                        $goods['pic_url'] = array_shift($img_srcs[1]);
                        $goods['pic_url'] = substr($goods['pic_url'],0,strrpos($goods['pic_url'],'_',1));
                        foreach($img_srcs[1] as $img_src){
                            $imgs[] = substr($img_src,0,strrpos($img_src,'_',1));
                        }
                    }
                }
                if(preg_match("/'reservePrice'\s*:\s*'([\d\.]+?)',/",$content,$price)){
                    $goods['price'] = (float)$price[1];
                }elseif(preg_match('/price:([\d\.]+?),/',$content,$price)){
                    $goods['price'] = (float)$price[1];
                }
                if(preg_match("/'categoryId'\s*:\s*'(\d+?)',/",$content,$cid)){
                    $goods['cid'] = (float)$cid[1];
                }elseif(preg_match("/\scid:'(\d+?)',/",$content,$cid)){
                    $goods['cid'] = (float)$cid[1];
                }
                if(empty($goods['title']) || empty($goods['pic_url']))
					return false;

				if($goods['cid'] > 0 && !FS("Goods")->getIsDisableByCid('taobao',$goods['cid']))
				{
					$result['status'] = -4;
					return $result;
				}

                if(count($imgs) > 0){
                    $result['imgs_html'] = $this->saveWebImg($imgs);
                }

                $shop = false;
                if(preg_match('/shopId:"(\d+?)",/',$content,$shopid)){
                    $shopid = (float)$shopid[1];
                    if($shopid > 0){
                        $shop = array();
                        $shop['shop_id'] = $shopid;
                        $shop['url'] = 'http://shop'.$shopid.'.taobao.com';
                        $disable_shop = FDB::fetchFirst('SELECT * FROM '.FDB::table('shop_disable')." WHERE shop_url = '".$shop['url']."'");
						if($disable_shop)
						{
							$result['status'] = -3;
							return $result;
						}
                        $content = @file_get_contents($shop['url']);
                        $content = @mb_convert_encoding($content,"UTF-8","gbk");
                        if(!empty($content)){
                            $content = preg_replace('/[\r\n]/','',$content);
                            if(preg_match('/"shopCategoryId":"(\d+?)",/',$content,$cid)){
                                $shop['cid'] = (float)$cid[1];
                            }
                            if(preg_match('/<title>(.*?)<\/title>/',$content,$title)){
                                $shop['name'] = substr($title[1],strpos($title[1],'-',1) + 1);
                                $shop['name'] = substr($shop['name'],0,strrpos($shop['name'],'-',1));
                            }
                            if(preg_match('/banner-box\s*?\{\s*?background\s*?:\s*?url\((.*?)\)/',$content,$shop_pic)){
                                $shop['pic_path'] = $shop_pic[1];
                            }elseif(preg_match('/<div class="banner-box">(.*?)<\/div>/',$content,$shop_pic)){
                                if(preg_match('/<img[^<]*?src="(.*?)"[^>]*?\/>/',$shop_pic[1],$shop_pic1)){
                                    $shop['pic_path'] = $shop_pic1[1];
                                }
                            }
                        }
                        if(!empty($shop['name'])){
                            if($shop['cid'] > 0){
                                $shop['cid'] = FS("Shop")->getCid('taobao',$shop['cid']);
                            }
                            $result['shop'] = $shop;
                        }else{
                            $shop = false;
                        }
                    }
                }

				$result['image_server'] = '';
				if($_FANWE['setting']['share_image_save_type'] == 0)
				{
					$image['path'] = $goods['pic_url'];
					$image['server_code'] = '';
				}
				elseif(!IS_UPYUN && FS("Image")->getIsServer())
				{
					$args = array();
					$args['pic_url'] = $goods['pic_url'];
					$server = FS("Image")->formatServer($_FANWE['request']['image_server'],'DE');
					$server = FS("Image")->getImageUrlToken($args,$server,1);
					$body = FS("Image")->sendRequest($server,'savetemp',true);
					if(empty($body))
						return false;

					$image = unserialize($body);
					$result['image_server'] = $server['image_server'];
				}
				else
				{
					$image = copyFile($goods['pic_url'],"temp",false);
					if($image === false)
						return false;
					$image['server_code'] = '';
				}
				$share_goods['img'] = $image['path'];

				if(isset($shop))
				{
					$shop_id = FS("Shop")->getShopIdByUrl($result['shop']['url']);
					if($shop_id == 0)
					{
						if(!empty($shop['pic_path']))
						{
							if($_FANWE['setting']['share_image_save_type'] == 0)
							{
								$image['path'] = $shop['pic_path'];
								$image['server_code'] = '';
							}
							elseif(!IS_UPYUN && FS("Image")->getIsServer())
							{
								$args = array();
								$args['pic_url'] = $shop['pic_path'];
								$server = FS("Image")->getImageUrlToken($args,'',1);
								$body = FS("Image")->sendRequest($server,'savetemp',true);
								if(!empty($body))
									$image = unserialize($body);
								else
									$image = false;
							}
							else
							{
								$image = copyFile($shop['pic_path'],"temp",false);
								if($image === false)
									$image['server_code'] = '';
							}

							if($image !== false)
							{
								$result['shop']['logo'] = $image['path'];
								$result['shop']['server_code'] = $image['server_code'];
							}
						}
					}
					else
					{
						$share_goods['shop_id'] = $shop_id;
						unset($result['shop']);
					}
				}

				$share_goods['id'] = 0;
				$share_goods['gid'] = $id;
				$share_goods['name'] = $goods['title'];
				$share_goods['desc'] = $goods['desc'];
				$share_goods['cid'] = FS("Goods")->getCid('taobao',$goods['cid']);
				$share_goods['price'] = $goods['price'];
				$share_goods['delist_time'] = str2Time($goods['delist_time']);
				$share_goods['server_code'] = $image['server_code'];
				$share_goods['pic_url'] = $goods['pic_url'].'_100x100.jpg';
				$share_goods['url'] = $goods['detail_url'];
				$result['item'] = $share_goods;
				setTempCache(md5($key),$result);
			}
		}
		else
		{
			$share_goods['pic_url'] = getImgById($share_goods['img_id'],100,100);
			if($share_goods['cid'] == 0)
			{
				$content = @file_get_contents($url);
                $content = @mb_convert_encoding($content,"UTF-8","gbk");
                if(!empty($content)){
                    $content = preg_replace('/[\r\n]/','',$content);
                    if(preg_match("/'categoryId'\s*:\s*'(\d+?)',/",$content,$cid)){
                        $cid = (float)$cid[1];
                    }elseif(preg_match("/\scid:'(\d+?)',/",$content,$cid)){
                        $cid = (float)$cid[1];
                    }
                    if($cid > 0)
                    {
                        $update_goods = array();
                        $share_goods['cid'] = $update_goods['cid'] = FS("Goods")->getCid('taobao',$cid);
                        FDB::update('goods',$update_goods,'id = '.$share_goods['id']);
                    }
                }
			}
			$result['item'] = $share_goods;
		}
		return $result;
    }

	public function getID($url)
	{
		$id = 0;
		$parse = parse_url($url);
		if(isset($parse['query']))
		{
            parse_str($parse['query'],$params);
			if(isset($params['id']))
				$id = $params['id'];
            elseif(isset($params['item_id']))
                $id = $params['item_id'];
			elseif(isset($params['default_item_id']))
                $id = $params['default_item_id'];
			elseif(isset($params['mallstItemId']))
                $id = $params['mallstItemId'];
        }
		return $id;
	}

	public function getKey($url)
	{
		$id = $this->getID($url);
		return 'taobao_'.$id;
	}

        public function saveWebImg($url_arr){
            global $_FANWE;
            $image_server = '';
            foreach ($url_arr as $url) {
                $result = array();
                if($_FANWE['setting']['share_image_save_type'] == 1)
                {
                        $img = getTempCache(md5($url));
                        if($img === NULL)
                        {
                                if(!IS_UPYUN && FS("Image")->getIsServer())
                                {
                                        $args = array();
                                        $args['pic_url'] = $url;
                                        $server = FS("Image")->formatServer($_FANWE['request']['image_server'],'DE');
                                        $server = FS("Image")->getImageUrlToken($args,$server,1);
                                        $body = FS("Image")->sendRequest($server,'savetemp',true);
                                        if(empty($body))
                                        {
                                                 exit();
                                        }
                                        $img = unserialize($body);
                                        if(empty($result['image_server'])){
                                            $image_server = $server['image_server'];
                                        }
                                }
                                else
                                {
                                        $img = copyFile($url,"temp",false);
                                        if($img === false)
                                        {
                                                if($image->error() == -105)
                                                        $result['status'] = -2;
                                                exit($image->error());
                                        }
                                        $img['server_code'] = '';
                                }
                        }

                        if($img)
                        {
                                setTempCache(md5($url),$img);
                                $result['status'] = 1;
                                $result['img'] = $img['url'];
                                $info = array('path'=>$img['path'],'url'=>$img['url'],'type'=>'default','server_code'=>$img['server_code'],'image_width'=>$img['width'],'image_height'=>$img['height']);
                                $result['info'] = base64_encode(json_encode($info));
                        }
                        else
                        {
                                exit('error_2');
                        }
                }
                else
                {
                        $result['img'] = $url;
                        $result['status'] = 1;
                        list($width, $height) = getimagesize($url);
                        $info = array('path'=>$url,'url'=>$url,'type'=>'default','server_code'=>'','image_width'=>$width,'image_height'=>$height);
                        $result['info'] = base64_encode(json_encode($info));
                }

                $args = array('result'=>$result);
                $img_html[] = tplFetch("services/share/pic_item",$args);
            }
            return $img_html;
       }
}
?>